package com.coolrui.config.dubbo;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.Map;

//这是一个服务提供端Filter,比plumelog官方的Filter晚执行
@Slf4j
@Activate(group = {CommonConstants.PROVIDER},order = 100)
public class DubboProviderFilter implements Filter {
    private static final String TRACE_ID = "trace_id";

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        // 日志相关参数：服务接口、方法、参数、当前RpcContext Attachments
        String serviceInterface = invoker.getInterface().getName(); // 如 com.example.DemoService
        String methodName = invocation.getMethodName();             // 如 getUser
        Object[] arguments = invocation.getArguments();             // 方法参数对象数组
        Map<String, String> attachments = invocation.getAttachments(); // 当前已有的Attachments

        // 构建参数字符串，如 [arg0=1001, arg1=John]
        StringBuilder paramsBuilder = new StringBuilder();
        if (arguments != null && arguments.length > 0) {
            paramsBuilder.append("[");
            for (int i = 0; i < arguments.length; i++) {
                if (i > 0) paramsBuilder.append(", ");
                Object arg = arguments[i];
                paramsBuilder.append("arg").append(i).append("=")
                        .append(arg != null ? arg.toString() : "null");
            }
            paramsBuilder.append("]");
        } else {
            paramsBuilder.append("无参数");
        }

        // 记录服务端日志
        log.info("《coolrui-dubbo-user》服务端Filter | 服务接口={}#{} | 参数={} | RpcContext Attachments={}",
                serviceInterface,
                methodName,
                paramsBuilder.toString(),
                JSONUtil.toJsonStr(attachments));
        return invoker.invoke(invocation);
    }
}
